import {
  request
} from "../../request/index.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    catesList: [],
    leftMenuList: [],
    rightMenuList: [],
    currentIndex: 0,
    scrollTop: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const Cates = wx.getStorageSync("cates");
    if (!Cates) {
      this.getCatesList();
    } else {
      if (Date.now() - Cates.time > 1000 * 60 * 5) {
        this.getCatesList();
      } else {
        let allCates = Cates.data;
        let leftMenuList, rightMenuList;
        leftMenuList = allCates.map(v => v.cat_name);
        rightMenuList = allCates[0].children;
        this.setData({
          catesList: allCates,
          leftMenuList,
          rightMenuList
        })
      }
    }

  },
  async getCatesList() {
    let data = await request({
      url: "https://api-hmugo-web.itheima.net/api/public/v1/categories"
    });
    // 将请求回来的数据存放到本地缓存中
    wx.setStorageSync("cates", {
      time: Date.now(),
      data: data.data.message
    });
    let leftMenuList, rightMenuList;
    leftMenuList = data.data.message.map(v => v.cat_name);
    rightMenuList = data.data.message[0].children;
    this.setData({
      catesList: data.data.message,
      leftMenuList,
      rightMenuList
    })
  },
  handleChangeItem(e) {
    console.log(e.currentTarget.dataset.num);
    let index = e.currentTarget.dataset.num;
    this.setData({
      rightMenuList: this.data.catesList[index].children,
      currentIndex: index,
      scrollTop: 0
    })
  }
})